package com.woniuxy.yoga.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.file.FileNameUtil;
import com.alipay.api.domain.StoreInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.yoga.business.client.CoachClient;
import com.woniuxy.yoga.business.client.OrderClient;
import com.woniuxy.yoga.business.client.ProductClient;
import com.woniuxy.yoga.business.dao.model.BusinessStore;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.yoga.business.dao.mapper.BusinessAccountMapper;
import com.woniuxy.yoga.business.dao.model.BusinessAccount;
import com.woniuxy.yoga.business.dao.model.BusinessStore;
import com.woniuxy.yoga.business.dao.mapper.BusinessStoreMapper;
import com.woniuxy.yoga.business.model.dto.businessstore.*;
import com.woniuxy.yoga.business.model.dto.orderinfo.OrderInfoDto;
import com.woniuxy.yoga.business.model.exception.BusinessException;
import com.woniuxy.yoga.business.model.exception.BusinessExceptionCode;
import com.woniuxy.yoga.business.model.param.businessaccount.UpdateHeaderParam;
import com.woniuxy.yoga.business.model.param.businessstore.BusinessStoreSelectPageParam;
import com.woniuxy.yoga.business.model.param.businessstore.BusinessStoreUpdateParam;
import com.woniuxy.yoga.business.service.BusinessStoreService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.yoga.commons.core.model.PageInfo;
import com.woniuxy.yoga.commons.core.model.Result;
import com.woniuxy.yoga.commons.core.statedata.BusinessState;
import com.woniuxy.yoga.commons.core.statedata.OrderState;
import com.woniuxy.yoga.commons.oss.util.OSSUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商家门店详情 服务实现类
 * </p>
 *
 * @author 韦用文,刘存益,郎腾霄
 * @since 2023年11月28日
 */
@Service
public class BusinessStoreServiceImpl extends ServiceImpl<BusinessStoreMapper, BusinessStore> implements BusinessStoreService {

    @Autowired
    private BusinessAccountMapper businessAccountMapper;
    @Autowired
    private BusinessStoreMapper businessStoreMapper;
    @Autowired
    private OrderClient orderClient;
    @Autowired
    private ProductClient productClient;
    @Autowired
    private CoachClient coachClient;
    @Autowired
    private OSSUtil ossUtil;

    /**
     * 平台分页查询门店信息
     * @param param
     * @return
     */
    @Override
    public PageInfo selectBusinessStore(BusinessStoreSelectPageParam param) {
        //创建分页查询对象
        Page<BusinessStore> page = new Page<BusinessStore>(param.getCurrent()==null?1:param.getCurrent(),
                param.getSize()==null?10:param.getSize());
        LambdaQueryWrapper<BusinessStore> wrapper = new LambdaQueryWrapper<BusinessStore>();
        //缴费状态条件是否为空
        if (param.getEnterMoneyState()!=null){
            wrapper.eq(BusinessStore::getEnterMoneyState, param.getEnterMoneyState());
        }
        //门店状态条件是否为空
        if (param.getStoreState()!=null){
            wrapper.eq(BusinessStore::getStoreState,param.getStoreState());
        }
        //门店名条件是否为空
        if (param.getStoreName()!=null&&(!param.getStoreName().equals(""))) {
            wrapper.like(BusinessStore::getStoreName,param.getStoreName());
        }
        //门店位置条件是否为空
        if (param.getStoreAddress()!=null&&(!param.getStoreAddress().equals(""))) {
            wrapper.like(BusinessStore::getStoreAddress,param.getStoreAddress());
        }
        //门店简介条件是否为空
        if (param.getStoreRemarks()!=null&&(!param.getStoreRemarks().equals(""))) {
            wrapper.like(BusinessStore::getStoreRemarks,param.getStoreRemarks());
        }
        //通过条件分页查出门店信息
        Page<BusinessStore> businessStorePage = businessStoreMapper.selectPage(page, wrapper);
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        List<BusinessStoreSelectDTO> storeSelectDTOS = BeanUtil.copyToList(businessStorePage.getRecords(), BusinessStoreSelectDTO.class);
        for (BusinessStoreSelectDTO storeSelectDTO : storeSelectDTOS) {
            BusinessAccount businessAccount = businessAccountMapper.selectById(storeSelectDTO.getAccountId());
            storeSelectDTO.setAccountName(businessAccount.getAccountName());
            storeSelectDTO.setAccountRealname(businessAccount.getAccountRealname());
        }
        pageInfo.setRecords(storeSelectDTOS);
        pageInfo.setPages(page.getPages());
        return pageInfo;
    }

    /**
     * 商家修改门店信息
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateBusinessStore(BusinessStoreUpdateParam param) {
        BusinessStore businessStore = businessStoreMapper.selectById(param.getStoreId());
        if (businessStore==null)throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_STORE_NOTEXITS);
        if (businessStore.getStoreState()==BusinessState.STORE_STATE_DELETE)throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_STORE_STATEERROR);
        LambdaUpdateWrapper<BusinessStore> wrapper = new LambdaUpdateWrapper<>();
        Boolean bool = false;
        //若修改电话条件不为空
        if (param.getStorePhone()!=null&&!param.getStorePhone().equals("")){
            wrapper.set(BusinessStore::getStorePhone,param.getStorePhone());
            bool = true;
        }
        //修改地址条件不为空
        if (param.getStoreAddress()!=null&&!param.getStoreAddress().equals("")){
            wrapper.set(BusinessStore::getStoreAddress,param.getStoreAddress());
            bool = true;
        }
        //修改简介条件不为空
        if (param.getStoreRemarks()!=null&&!param.getStoreRemarks().equals("")){
            wrapper.set(BusinessStore::getStoreRemarks,param.getStoreRemarks());
            bool = true;
        }
        System.out.println(param.getOpenTimeStrs().get(0).substring(11,16)+param.getOpenTimeStrs().get(1).substring(11,16));
        //修改营业时间条件不为空
        if (param.getOpenTimeStrs()!=null&&param.getOpenTimeStrs().size()>0&&param.getWeekTime()!=null&&!param.getWeekTime().equals("")) {
            List<String> openTimeStrs = param.getOpenTimeStrs();
            String openTime = null;
            openTime =param.getWeekTime()+" "+openTimeStrs.get(0).substring(11,16)+"-"+openTimeStrs.get(1).substring(11,16);
            System.out.println("----------"+openTime);
            wrapper.set(BusinessStore::getOpenTime,openTime);
            bool = true;
        }
        //修改门店名条件不为空
        if (param.getStoreName()!=null&&!param.getStoreName().equals("")){
            wrapper.set(BusinessStore::getStoreName,param.getStoreName());
            bool = true;
        }
        //修改门店头像条件不为空
        if (param.getStoreHeader()!=null&&!param.getStoreHeader().equals("")){
            wrapper.set(BusinessStore::getStoreHeader,param.getStoreHeader());
            bool = true;
        }
        if (bool) {
            wrapper.eq(BusinessStore::getStoreId,param.getStoreId());
            businessStoreMapper.update(null,wrapper);
        }
        return bool;
    }

    /**
     * 注销门店
     * @param storeId
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void deleteBusinessStore(Integer storeId) {
        BusinessStore businessStore = businessStoreMapper.selectById(storeId);
        if (businessStore==null)throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_STORE_NOTEXITS);
        if (businessStore.getStoreState()==BusinessState.STORE_STATE_DELETE)throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_STORE_STATEERROR);
        //是否存在未完成的业务
        Result<List<OrderInfoDto>> orderResult = orderClient.listOrdersByStoreId(businessStore.getStoreId());
        if (orderResult.getCode()!=200) {
            throw new BusinessException(orderResult.getCode(),orderResult.getMessage());
        }
        List<OrderInfoDto> orderInfoDtos = orderResult.getData();
        for (OrderInfoDto orderInfoDto : orderInfoDtos) {
            if (orderInfoDto.getOrderState()!= OrderState.ORDER_STATE_CANCEL&&orderInfoDto.getOrderState()!=OrderState.ORDER_STATE_DONE) {
                throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ORDER_NOTCOMPLETED);
            }
        }
        //员工账号全部注销
        Result<?> result = coachClient.removeCoach(businessStore.getStoreId());
        if (result.getCode()==500) {
            throw new BusinessException(500,"系统错误");
        }
        if (result.getCode()!=200) {
            throw new BusinessException(result.getCode(),result.getMessage());
        }
        //产品全部删除
        Result<?> productResult = productClient.removeProduct(businessStore.getStoreId());
        if (productResult.getCode()==500) {
            throw new BusinessException(500,"系统错误");
        }
        if (productResult.getCode()!=200) {
            throw new BusinessException(productResult.getCode(),productResult.getMessage());
        }
        //注销门店
        businessStore.setStoreState(BusinessState.STORE_STATE_DELETE);
        businessStoreMapper.updateById(businessStore);
    }

    /**
     * 门店歇业
     * @param storeId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void disableBusinessStore(Integer storeId) {
        //门店是否存在
        BusinessStore businessStore = businessStoreMapper.selectById(storeId);
        if (businessStore==null)throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_STORE_NOTEXITS);
        //门店状态是否正常
        if (businessStore.getStoreState()!=BusinessState.STORE_STATE_NORMAL)throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_STORE_STATEERROR);
        //门店歇业
        businessStore.setStoreState(BusinessState.STORE_STATE_DISABLE);
        businessStoreMapper.updateById(businessStore);
    }

    /**
     * 门店营业
     * @param storeId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void normalBusinessStore(Integer storeId) {
        //门店是否存在
        BusinessStore businessStore = businessStoreMapper.selectById(storeId);
        if (businessStore==null)throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_STORE_NOTEXITS);
        //门店状态是否是歇业
        if (businessStore.getStoreState()!=BusinessState.STORE_STATE_DISABLE)throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_STORE_STATEERROR);
        //门店是否已缴费
        if (businessStore.getEnterMoneyState()!= BusinessState.ENTER_MONEY_STATE_PAYED) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_PAYMENT_NOTPAY);
        }
        //门店是否完善简介信息
        if (businessStore.getStoreRemarks()==null||businessStore.getStoreRemarks().equals("")) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_STOREREMARKS_NULL);
        }
        //门店是否完善营业信息
        if (businessStore.getOpenTime()==null||businessStore.getOpenTime().equals("")) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_OPENTIME_NULL);
        }
        businessStore.setStoreState(BusinessState.STORE_STATE_NORMAL);
        businessStoreMapper.updateById(businessStore);
    }

    /**
     * 根据商家id查询门店信息,商家状态正常、门店状态正常且已缴费
     * @param accountId
     * @return
     */
    @Override
    public BusinessStoreByAccountIdDTO selBusinessStoreByAccountId(Integer accountId) {
        //查看商家账号是否存在
        BusinessAccount businessAccount = businessAccountMapper.selectById(accountId);
        if (businessAccount==null) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_NOTEXITS);
        }
        //商家状态是否正常
        if (businessAccount.getAccountState()!= BusinessState.BUSINESS_ACCOUNT_STATE_NORMAL) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_STATEERROR);
        }
        //查询状态正常且已缴费的门店信息
        LambdaQueryWrapper<BusinessStore> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusinessStore::getAccountId,accountId)
                .eq(BusinessStore::getEnterMoneyState,BusinessState.ENTER_MONEY_STATE_PAYED)
                .notIn(BusinessStore::getStoreState,BusinessState.STORE_STATE_DELETE);
        BusinessStore businessStore = businessStoreMapper.selectOne(queryWrapper);
        return BeanUtil.toBean(businessStore,BusinessStoreByAccountIdDTO.class);
    }

    /**
     * 商家查询门店信息
     * @param businessId
     * @return
     */
    @Override
    public BusinessStoreByIdDTO storeSelBusinessStore(Integer businessId) {
        //查询商家账号是否存在
        BusinessAccount businessAccount = businessAccountMapper.selectById(businessId);
        if (businessAccount==null)throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_NOTEXITS);
        //查询账号状态是否正常
        if (businessAccount.getAccountState()!=BusinessState.BUSINESS_ACCOUNT_STATE_NORMAL)throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_STATEERROR);
        //查询门店信息
        BusinessStore businessStore = businessStoreMapper.selectOne(
                new LambdaQueryWrapper<BusinessStore>().eq(BusinessStore::getAccountId,businessId).notIn(BusinessStore::getStoreState,BusinessState.STORE_STATE_DELETE)
        );
        return BeanUtil.toBean(businessStore,BusinessStoreByIdDTO.class);
    }

    /**
     * 通过门店ID查询门店信息
     * @param storeId
     * @return
     */
    @Override
    public BusinessStoreDTO selByStoreId(Integer storeId) {
        //是否存在该门店
        BusinessStore businessStore = businessStoreMapper.selectById(storeId);
        if (businessStore==null) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_STORE_NOTEXITS);
        }
        //该门店是否已被注销
        if (businessStore.getStoreState()== BusinessState.STORE_STATE_DELETE) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_STORE_DELETED);
        }
        //将门店信息转成DTO
        BusinessStoreDTO businessStoreDTO = BeanUtil.toBean(businessStore, BusinessStoreDTO.class);
        return businessStoreDTO;
    }
    /**
     * 查询门店信息集合
     * @return
     */
    @Override
    public List<SelBusinessStoreDTO> searchBusinessStore() {
        LambdaQueryWrapper<BusinessStore> queryWrapper = new LambdaQueryWrapper<>();
        //过滤已注销的门店
        queryWrapper.notIn(BusinessStore::getStoreState,BusinessState.STORE_STATE_DELETE);
        List<BusinessStore> businessStores = businessStoreMapper.selectList(queryWrapper);
        //转换成需要的门店实体
        List<SelBusinessStoreDTO> selBusinessStoreDTOS = BeanUtil.copyToList(businessStores, SelBusinessStoreDTO.class);
        return selBusinessStoreDTOS;
    }
    /**
     * 商家修改门店头像
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStoreHeader(UpdateHeaderParam param) throws Exception {
        //查询账号是否存在
        BusinessAccount businessAccount = businessAccountMapper.selectById(param.getAccountId());
        if (businessAccount==null) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_NOTEXITS);
        }
        //账号状态是否正常
        if (businessAccount.getAccountState()!= BusinessState.BUSINESS_ACCOUNT_STATE_NORMAL) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_STATEERROR);
        }
        //根据账号查询门店信息
        LambdaQueryWrapper<BusinessStore> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BusinessStore::getAccountId,param.getAccountId()).notIn(BusinessStore::getStoreState,BusinessState.STORE_STATE_DELETE);
        BusinessStore businessStore = businessStoreMapper.selectOne(wrapper);
        //上传图片
        MultipartFile image = param.getAccountHeader();
        if (image ==null) throw new Exception("传入图片不能为空");
        //获取上传图片的文件名
        String filename = image.getOriginalFilename();
        //获取图片的类型
        String name = filename.substring(filename.lastIndexOf(".")+1);
        //调用API上传
        String imagePath = ossUtil.uploadFile(image.getInputStream(),name);
        //删除原图片
        String path = FileNameUtil.getName(businessStore.getStoreHeader());
        ossUtil.deleteFile(path,"liucunyi");
        //修改数据库中的路径
        businessStore.setStoreHeader(imagePath);
        businessStoreMapper.updateById(businessStore);
    }
}
